package com.h2cloud.Proxy._5_test;


/**
 * @Package: com.h2cloud.Proxy._5_test
 * @ClassName: Main
 * @Author: h2cloud
 * @CreateTime: 2023/10/16 11:05 下午
 * @Description:
 */


import net.sf.cglib.core.ClassGenerator;
import net.sf.cglib.core.DefaultGeneratorStrategy;
import net.sf.cglib.core.GeneratorStrategy;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import java.lang.reflect.Method;

public class Main {
	public static void main(String[] args) throws Exception {
		// 使用 ClassGenerator 创建代理类的 Class 对象
		Class<?> proxyClass = createProxyClass(TargetClass.class, new TargetClassInterceptor());

		// 实例化代理类
		TargetClass proxy = (TargetClass) proxyClass.newInstance();
		proxy.doSomething();
	}

	// 创建代理类的 Class 对象
	public static Class<?> createProxyClass(Class<?> targetClass, MethodInterceptor interceptor) {
		Enhancer enhancer = new Enhancer();
		enhancer.setSuperclass(targetClass);
		enhancer.setCallback(interceptor);

		// 使用自定义 GeneratorStrategy 生成代理类的 Class 对象
		GeneratorStrategy strategy = new DefaultGeneratorStrategy() {
			@Override
			protected byte[] transform(byte[] b) throws Exception {
				// 在这里可以对字节码进行自定义处理，如果不需要特殊处理，直接返回原始字节码即可
				return b;
			}
		};
		enhancer.setStrategy(strategy);

		// 生成代理类的 Class 对象
		return enhancer.createClass();
	}

	static class TargetClass {
		public void doSomething() {
			System.out.println("TargetClass: Doing something...");
		}
	}

	static class TargetClassInterceptor implements MethodInterceptor {
		@Override
		public Object intercept(Object obj, Method method, Object[] args, net.sf.cglib.proxy.MethodProxy proxy)
				throws Throwable {
			System.out.println("Before method: " + method.getName());
			Object result = proxy.invokeSuper(obj, args);
			System.out.println("After method: " + method.getName());
			return result;
		}
	}
}



